const App = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    dataType: 'assign',
    isLoading: true,
    page: 1,
    no_more: false,
    rand:1, 

    shop_cate:0,//分类
    coupon_type:0,//类别
    people_num:0,//参与人数
    time:0,//参与时间

    shoppingMall:[],
    shoppingMallName:'',
    shoppingMallId:'',
    // 下拉菜单
    first: '选择商城',
    second: '筛选',
    // thirds: '房型',
    // fours: '筛选',
    // _num: 0,
    // _res: 0,
    dist:[],
    shopping_mall_city:'',
    shopping_mall_district:'',
    // 筛选
    shop_cate_res: [],
    people_num_res: [{ id: 2, name: '2人' }, { id: 3, name: '3人' }, { id: 4, name: '4人以上' }],
    
    
    one: 0,
    two: 0,
    third: 0,
    four: 0,
    // five: 0,
    // six: 0,
    // seven: 0,


  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //let shopping_mall_city = wx.getStorageSync('shopping_mall_city');//城市名称
    let shopping_mall_city = '杭州市';//城市名称
    //缓存中有
    if (shopping_mall_city) {
      this.setData({
        shopping_mall_city: shopping_mall_city
      })
    }
   
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let team = this.data.list;
    //获取分类
    this.getShopCate();
    //获取 区信息
    this.getDistrict();
    // 获取 商城地址
    //this.getShoppingMall();
    // 获取信息列表
    if(!team){
      this.getTeamList();
    }
    //积分获得介绍
    this.changeNav();

    if (this.data.dataType == 'allInit'){
      this.countDown();
    }
  },

  onHide: function () {
    //页面隐藏
    // console.log('onHide');
    clearInterval(this.data.timer);
  },
  onUnload: function () {
    //页面关闭
    // console.log('onUnload');
    clearInterval(this.data.timer);
  },

  changeNav:function(){
    //assign makeup recharge allInit
    let dataType = this.data.dataType;
    if (dataType == 'assign'){
      this.setData({
        initContent: '*每消费1元获得1个积分'
      })
    }
    if (dataType == 'makeup') {
      this.setData({
        initContent: '*组合卷积分翻倍'
      })
    }
    if (dataType == 'recharge') {
      this.setData({
        initContent: '*店铺充值积分翻倍'
      })
    }
    if (dataType == 'allInit') {
      this.setData({
        initContent: '*消费获得相应积分'
      })
    }

  },

  onReady: function () {
    //页面渲染完成 第三运行
    //console.log('onReady');
  },

  getShopCate:function(){
    let _this = this;
    App._get('shop/getShopCate', {
    }, function (result) {
      //console.log(result);
      _this.setData({
        shop_cate_res: result.data.shopCate
      });
    });
  },

  //获取区信息
  getDistrict:function(){
    let _this = this;
    let user_address_id =  this.data.shoppingMallId
    let shopping_mall_city = this.data.shopping_mall_city;
    let shopping_mall_district = this.data.shopping_mall_district;
    
    App._get('Shopping_mall/getDistrict', {
      shopping_mall_id: user_address_id, 
      shopping_mall_city: shopping_mall_city,
      shopping_mall_district: shopping_mall_district
    }, function (result) {
      _this.setData({
        dist: result.data.list
      });
    });
  },
  //获取商城地址
  // getShoppingMall:function(){
  //   let _this = this;
  //   //let user_address_id = wx.getStorageSync('user_address_id');
  //   let user_address_id = this.data.shoppingMallId ? this.data.shoppingMallId : wx.getStorageSync('user_address_id') ;
  //   App._get('Shopping_mall/getShoppingMall', {
  //     shopping_mall_id: user_address_id
  //   }, function (result) {
  //     //console.log(result);
  //     _this.setData({
  //       shoppingMall: result.data.list
  //     });
  //   });
  // },

  /**
   * 获取我的团队列表
   */
  getTeamList: function(isNextPage, page) {
    let urls = {
      receive: 'coupon/lists?type=receive',//获取优惠券
      assign: 'coupon/lists?type=assign',//拼团卷
      makeup: 'coupon_makeup_do/lists',//组合卷
      recharge:'recharge/lists',//店铺充值
      allInit: 'doing/getList?type=allInit',//发起优惠券
    };
    let _this = this;
    
    App._get(urls[_this.data.dataType], {
      page: page || 1, 
      rand: _this.data.rand,
      shoppingMallId: _this.data.shoppingMallId,
      dataType: _this.data.dataType,

      shop_cate: _this.data.shop_cate,
      coupon_type: _this.data.coupon_type,//类别
      people_num: _this.data.people_num,//参与人数
      time: _this.data.time,//参与时间
    }, function(result) {
       console.log(result);
      // 领取优惠券 页面
      if (_this.data.dataType == 'receive' || _this.data.dataType == 'assign' || _this.data.dataType == 'makeup' || _this.data.dataType == 'recharge'){
        // 创建页面数据
        let tang = _this.createData(result.data, isNextPage);
        _this.setData(tang);
      }
      //所有发起的优惠券
      if (_this.data.dataType == 'allInit'){
        let resList = result.data.list,
          dataList = _this.data.list;
          
        //添加图片路径
        for (let i = 0; i < resList.data.length; i++) {
          resList.data[i]['root'] = App.root;
        }
        //console.log(resList.data);
        if (isNextPage == true) {
          _this.setData({
            'list.data': dataList.data.concat(resList.data),
            isLoading: false,
          });
        } else {
          _this.setData({
            list: resList,
            isLoading: false,
          });
        }
      }

      if (_this.data.dataType == 'allInit'){
        _this.countDown();
      }
      //console.log(_this.data.list.data);
    });
  },

  /**
   * 创建页面数据
   */
  createData: function(data, isNextPage) {
    data['isLoading'] = false;
    // 列表数据
    let dataList = this.data.list;
    if (isNextPage == true && (typeof dataList !== 'undefined')) {
      data.list.data = dataList.data.concat(data.list.data);
    }
    //添加图片路径
    //console.log(data.list.data);
    for (let i = 0;i < data.list.data.length;i++){
      data.list.data[i]['root'] = App.root;
    }
    // 设置swiper的高度
    this.setSwiperHeight();
    return data;
  },

  /**
   * 下拉到底加载数据
   */
  triggerDownLoad: function() {
    // 已经是最后一页
    if (this.data.page >= this.data.list.last_page) {
      this.setData({
        no_more: true
      });
      return false;
    }
    this.getTeamList(true, ++this.data.page);
  },
  //随机刷新
  rand:function(){
    this.setData({
      isLoading: true,
      disdataTypet: 1,
      page: 1,
      no_more: false,
      rand: 2
    });
    this.getTeamList();
  },
  //刷新页面
  newPage:function(){
    this.setData({
      isLoading: true,
      disdataTypet: 1,
      page: 1,
      no_more: false,
      rand: 1,
      currentTab:3
    });
    this.getTeamList();

  },
  //返回正常排序
  gotoSort:function(){
    this.setData({
      isLoading: true,
      disdataTypet: 1,
      page: 1,
      no_more: false,
      rand: 1
    });
    this.getTeamList();
  },
  /**
   * 设置swiper的高度
   */
  setSwiperHeight: function(isTap) {
    // 获取系统信息(拿到屏幕宽度)
    let systemInfo = wx.getSystemInfoSync(),
      rpx = systemInfo.windowWidth / 750, // 计算rpx
      tapHeight = isTap ? Math.floor(rpx * 82) : 0, // tap高度
      peopleHeight = Math.floor(rpx * 65), // people高度
      tang = Math.floor(rpx * 170), 
      swiperHeight = systemInfo.windowHeight - tapHeight - peopleHeight-tang-35; // swiper高度
    
    this.setData({
      swiperHeight
    });
  },
  /**
   * 表单提交
   */
  // saveData: function (e) {
  //   let _this = this;
  //   let shoppingMallId = _this.data.shoppingMallId;
  //   App._get('user.dealer.team/lists', {
  //     page: 1,
  //     shoppingMallId: shoppingMallId
  //   }, function (result) {
  //     // 创建页面数据
  //     _this.setData(_this.createData(result.data));
  //   });
  // },

  /**
   * 修改地区
   */
  // bindPickerChange: function (e) {
  //   let index = e.detail.value;
  //   this.setData({
  //     shoppingMallName: this.data.shoppingMall[index]['shopping_mall_cont'],
  //     shoppingMallId: this.data.shoppingMall[index]['shopping_mall_id']
  //   })
  // },


  //下拉js
  isShow: true,
  currentTab: 0,

  // 下拉切换
  hideNav: function () {
    this.setData({
      displays: "none",
      currentTab: 3,
    })
  },
  // 区域
  tabNav: function (e) {
    let dis = this.data.displays;
    if (dis == 'block' && this.data.currentTab === e.target.dataset.current){
      this.setData({
        displays: "none",
      })
    }else{
      this.setData({
        displays: "block",
      })
    }
    
    if (this.data.currentTab === e.target.dataset.current) {
      //return false;
      this.setData({
        currentTab: 3,
      })
    } else {
      var showMode = e.target.dataset.current == 0;
      this.setData({
        currentTab: e.target.dataset.current,
        isShow: showMode
      })
    }
  },
  // 下拉切换中的切换
  // 选择 区
  selected: function (e) {
    let _this = this;
    let dist_id = e.currentTarget.dataset.id;
    //let user_address_id = wx.getStorageSync('user_address_id');//商城id
    let user_address_id = this.data.shoppingMallId
    App._get('Shopping_mall/clickDist', {
      dist_id: dist_id,
      shopping_mall_id: user_address_id
    }, function (result) {
      _this.setData({
        dist: result.data.dist_res
      });
      _this.setData({
        shoppingMall: result.data.mall
      });
    });


  },
  
  // 商城选择
  clickShoppingMall: function (e) {
    let shoppingMall = this.data.shoppingMall;
    for (let i = 0; i < shoppingMall.length; i++) {
      shoppingMall[i]['selected'] = 'add_city';
      if (e.currentTarget.dataset.id == shoppingMall[i]['id']){
        shoppingMall[i]['selected'] = 'add_adress';
      }
    };
    this.setData({
      shoppingMall: shoppingMall,
      shoppingMallId: e.currentTarget.dataset.shopping_mall_id,
      shoppingMallName: e.currentTarget.dataset.name
    });
    this.getTeamList();//显示 社交对象
    this.setData({
      displays: "none",
      currentTab:0
    })
  },

  //显示全部
  allShopping: function () {
    let shoppingMall = this.data.shoppingMall;
    for (let i = 0; i < shoppingMall.length; i++) {
      shoppingMall[i]['selected'] = 'add_city';
    };
    this.setData({
      shoppingMall: shoppingMall,
      shoppingMallId: '',
      shoppingMall:[]
    });
    //获取 区信息
    this.getDistrict();
    this.getTeamList();//显示 社交对象
    this.setData({
      isLoading: true,
      disdataTypet: 1,
      page: 1,
      no_more: false,
      rand: 1,
      displays: "none",
      currentTab:3,
      shoppingMallName:''
    });
  },
  
  clickMum: function (e) {
    this.setData({
      _mum: e.target.dataset.num
    })
    this.setData({
      displays: "none"
    })
    var text = this.data.name
  },
 
  clickCum: function (e) {
    this.setData({
      _cum: e.target.dataset.num
    })
    this.setData({
      displays: "none"
    })
    var text = this.data.name
    //console.log(text)
  },
  
  // 售价
  clickNum: function (e) {
    //console.log(e.target.dataset.num)
    this.setData({
      _num: e.target.dataset.num
    })
    this.setData({
      second: e.target.dataset.name
    })
    this.setData({
      displays: "none"
    })
    var text = this.data.name
    //console.log(text)
  },
  
  // 房型
  clickHouse: function (e) {
    this.setData({
      _res: e.target.dataset.num
    })
    this.setData({
      thirds: e.target.dataset.name
    })
    this.setData({
      displays: "none"
    })
  },
  

  // 筛选
  chose_shop_cate:function(e){
    this.setData({
      shop_cate: e.currentTarget.dataset.id,
      one: e.currentTarget.dataset.id
    })
  },

  chose_coupon_type: function (e) {
    this.setData({
      coupon_type: e.currentTarget.dataset.id,
      two: e.currentTarget.dataset.id
    })
  },

  chose_people_num: function (e) {
    this.setData({
      people_num: e.currentTarget.dataset.id,
      third: e.currentTarget.dataset.id
    })
  },

  chose_time_res: function (e) {
    this.setData({
      time: e.currentTarget.dataset.id,
      four: e.currentTarget.dataset.id
    })
  },

  //确认 
  queren: function (e) {
    let _this = this;
    this.getTeamList();
    this.setData({
      isLoading: true,
      page: 1,
      no_more: false,
      displays: "none",
      currentTab: 3,
      is_xuan: true
    })
  },

  //清除
  qingchu: function () {
    this.setData({
      isLoading: true,
      page: 1,
      no_more: false,

      shop_cate: 0,//分类
      coupon_type: 0,//类别
      people_num: 0,//参与人数
      time: 0,//参与时间
      one: 0,
      two: 0,
      third: 0,
      four:0,
      displays: "none",
      currentTab: 3,
      is_xuan: false
    })
    this.getTeamList();
  },

  // choseTxtColor: function (e) {
  //   var id = e.currentTarget.dataset.id;  //获取自定义的ID值  
  //   //console.log(e.currentTarget.dataset.id)
  //   this.setData({
  //     one: id
  //   })
  // },
  // chaoxiang: function (e) {
  //   var id = e.currentTarget.dataset.id;  //获取自定义的ID值  
  //   this.setData({
  //     two: id
  //   })
  // },
  // louceng: function (e) {
  //   var id = e.currentTarget.dataset.id;  //获取自定义的ID值  
  //   this.setData({
  //     third: id
  //   })
  // },
  // zhuangxiu: function (e) {
  //   var id = e.currentTarget.dataset.id;  //获取自定义的ID值  
  //   this.setData({
  //     four: id
  //   })
  // },
  // leibei: function (e) {
  //   var id = e.currentTarget.dataset.id;  //获取自定义的ID值  
  //   this.setData({
  //     five: id
  //   })
  // },
  // tese: function (e) {
  //   var id = e.currentTarget.dataset.id;  //获取自定义的ID值  
  //   this.setData({
  //     six: id
  //   })
  // },
  // paixu: function (e) {
  //   var id = e.currentTarget.dataset.id;  //获取自定义的ID值  
  //   this.setData({
  //     seven: id
  //   })
  // },

  /**
   * 切换标签
   */
  bindHeaderTap: function (e) {

    this.setData({
      dataType: e.currentTarget.dataset.type
    })

    this.setData({
      isLoading: true,
      disdataTypet: 1,
      page: 1,
      no_more: false,
      rand: 1,
      currentTab: 3
    });
    this.getTeamList();
    this.changeNav();

    // let urls = {
    //   receive: '/pages/coupon/index?type=receive',
    //   assign: '/pages/order/index?type=assign',
    //   init: '/pages/doing/index?type=init',
    // };
    // // 转跳指定的页面
    // wx.navigateTo({
    //   url: urls[e.currentTarget.dataset.type]
    // })
  },

  //跳转 用户详情页
  goToDetail: function (e) {
    let user_id = e.currentTarget.dataset.user_id;
    wx.navigateTo({
      url: '/pages/social/detail?user_id=' + user_id
    })
  },

  dump_assign_coupon: function (e) {
    let doing_id = e.currentTarget.dataset.doing_id;
    let coupon_id = e.currentTarget.dataset.coupon_id;
    let user_coupon_id = e.currentTarget.dataset.user_coupon_id;
    let status = this.data.dataType;
    //console.log(doing_id);
    wx.navigateTo({
      url: '/pages/coupon/detail?status=' + status + '&coupon_id=' + coupon_id + '&user_coupon_id=' + user_coupon_id + '&doing_id=' + doing_id
    })
  },

  dump_makeup: function (e) {
    let doing_id = e.currentTarget.dataset.doing_id;
    let coupon_id = e.currentTarget.dataset.coupon_id;
    let user_coupon_id = e.currentTarget.dataset.user_coupon_id;
    let status = this.data.dataType;
    wx.navigateTo({
      url: '/pages/coupon/detail?status=' + status + '&coupon_id=' + coupon_id + '&user_coupon_id=' + user_coupon_id + '&doing_id=' + doing_id
    })
  },

  dump_recharge:function(e){
    let id = e.currentTarget.dataset.id;
    let status = this.data.dataType;
    wx.navigateTo({
      url: '/pages/coupon/recharge?status=' + status +'&id=' + id 
    })
  },

  goRenzheng:function(){
    wx.navigateTo({
      url: '/pages/address/index'
    })
  },

  timeFormat(param) {//小于10的格式化函数
    return param < 10 ? '0' + param : param;
  },

  countDown() {//倒计时函数
    let _this = this;
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    //let endTimeList = this.data.actEndTimeList;
    let endTimeList = _this.data.list;
    let countDownArr = [];
    if (endTimeList.data) {
      for (let i = 0; i < endTimeList.data.length; i++) {
        let endTime = new Date(endTimeList.data[i].timett).getTime();
        let obj = null;
        // 如果活动未结束，对时间进行处理
        if (endTime - newTime > 0) {
          let time = (endTime - newTime) / 1000;
          // 获取天、时、分、秒
          let day = parseInt(time / (60 * 60 * 24));
          let hou = parseInt(time % (60 * 60 * 24) / 3600);
          let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
          let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
          obj = {
            day: this.timeFormat(day),
            hou: this.timeFormat(hou),
            min: this.timeFormat(min),
            sec: this.timeFormat(sec)
          }
        } else {//活动已结束，全部设置为'00'
          obj = {
            day: '00',
            hou: '00',
            min: '00',
            sec: '00'
          }
        }
        endTimeList.data[i]['time'] = obj;
      }
      // 渲染，然后每隔一秒执行一次倒计时函数
      this.setData({ 'list.data': endTimeList.data })
    }
    this.setData({ timer: setTimeout(this.countDown, 1000)})
    
  },

})